

<template>
  <div>

    
    
    
    <!-- table 组件-->
    <dyn-table
            :alias="'purchaseContractFileInfo'"
            :queryParams="query"
            :listBtnObj="dynTableData.listBtnObj"
            :listTable="dynTableData.listTable"
            :eventName="eventName"
            ref="dynTableBox"
    />
    <!-- 查看表单 -->
    <purchaseContractFileInfo-show ref="purchaseContractFileInfoShow"/>
    <!-- 新建表单 -->
    <purchaseContractFileInfo-add ref="purchaseContractFileInfoAdd"  @created="doQueryList({ page: 1 })"/>
    <!-- 编辑表单 -->
    <purchaseContractFileInfo-edit ref="purchaseContractFileInfoEdit"  @updated="doQueryList({})"/>

  </div>
</template>


<script>
import purchaseContractFileInfoAdd from './add'
import purchaseContractFileInfoEdit from './edit'
import purchaseContractFileInfoShow from './show'

import { getOffsetTop, queryToString } from '@/utils/public'
import purchaseContractFileInfoApi from '@/api/platformJiaojianyi/purchaseContractFileInfo'
import commonApi from '@/api/platformJiaojianyi/common'
import purchaseContractApi from '@/api/platformJiaojianyi/purchaseContract'

import DynTable from '@/components/DynTable'
import specialAttr from '@/utils/special-attr'
import tableConfigApi from '@/api/platformJiaojianyi/tableConfig'
import dynTableApi from '@/api/platformJiaojianyi/dynTable'



export default {
  name: 'PurchaseContractFileInfoTable',
  components: {
    DynTable,
    purchaseContractFileInfoAdd,
    purchaseContractFileInfoEdit,
    purchaseContractFileInfoShow
  },
  data() {
    return {
      treeParentLabel: '',
      menusOne: {},
      codeRules: {},
      applicationCode: '',
        // 组件内部调用的查询和重置方法
      eventName: {
        search: 'handleQuery',
        reset: 'handleReset',
        drags: 'handleDrags',//拖拽区确定按钮
        order: 'sortChange',
        page: 'handlePage'
      },
      // 动态表格属性
      dynTableData: {
        listBtnObj: [],
        listTable: {},
        inLineBtnList: []
      },
      listQuery: {},
      tableHeight: -1,
      options: {
        purchaseContract: [],
      },
      query: {
        pageNum: 1,
        pageSize: 20,
        sortBy: 'id',
        sortOrder: 'desc',
        q: ''
      },
      showPage: false
    }
  },
  created() {
    Promise.all([
      this.initApi()
    ]).then(() =>{
    
      let objDatas = [];
      let code = sessionStorage.getItem('routerCode');
      let menus = JSON.parse(sessionStorage.getItem('routerMenus'));
      console.log(code)
      console.log(menus)
      if(menus!=null){
        menus.forEach((item) => {
          if(item.menuCode==code){
            objDatas.push(item)
          }
        })
      }
      this.menusOne = JSON.parse(JSON.stringify(objDatas[0]))
      this.genDynTable(JSON.parse(JSON.stringify(this.menusOne)));
      // 新建的时候编码规则调取接口接口赋值
      let applicationEntry = JSON.parse(sessionStorage.getItem('userinfos')).applications
      console.log('99',applicationEntry)
      for (let i = 0; i < applicationEntry.length; i++) {
        let item = applicationEntry[i];
        if (this.menusOne.appId === item.id) {
          this.applicationCode = item.code;
          break;
        }
      }
      this.handleCode()
    })
  },
  methods: {
    /**预留表格点击事件*/
    cellClick(row, column, cell, event) {
      console.log('======================')
      console.log('row', row)
      console.log('row', column)
      console.log('row', cell)
      console.log('row', event)
    },
    async initApi () {
      let str = 'insertFormData'//新增编辑展示显示的formdata
      if(this.entryFrom === 'add' || !this.entryFrom){
        str = 'insertFormData'
      }else if(this.entryFrom === 'edit'){
        str = 'updateFormData'
      }else if(this.entryFrom === 'show'){
        str = 'detailFormData'
      }
      let objDatas = [];
      let code = sessionStorage.getItem('routerCode');
      let menus = JSON.parse(sessionStorage.getItem('routerMenus'));
      console.log(code)
      console.log(menus)
      if(menus!=null){
        menus.forEach((item) => {
          if(item.menuCode==code){
            objDatas.push(item)
          }
        })
      }
      let menusOne = JSON.parse(JSON.stringify(objDatas[0]))
      let formObj = JSON.parse(JSON.stringify(menusOne))
      this.showPage = formObj.listTable.showPage
      this.treeParentLabel = formObj.listTable.treeParentLabel
      for (let i = 0; i <  formObj.listTable.tableHeader.length; i ++) {
          let obj = formObj.listTable.tableHeader[i];
          // URL
          if (obj.fieldDataType && obj.fieldDataType == 2) {
            let {url, label, value} = obj.dataSources[0];
            let {data} = await purchaseContractFileInfoApi.dataApi({url, label, value}) || {}
            this.options[obj.webEntityData] = data;
          } 
          // 静态字符串
          else if (obj.fieldDataType && obj.fieldDataType == 4) {
            let json = obj.dataJson;
            this.options[obj.webEntityData] = JSON.parse(json)
          }
          // 外键
          else if (obj.fieldDataType && (obj.fieldDataType == 3 || obj.fieldDataType == 5)) {
            await this['get' + obj.foreignDataClassName + 'Api'](obj.mainFieldLabelName)
          }
      }
    },
    // 新建的时候编码规则调取接口接口赋值
    async handleCode(parentCode){
      let i;
      let arr = this.menusOne['insertFormData'].elements
      for(i=0;i<arr.length;i++){
        //编码规则校验
        if(arr[i].isSerialNumber==true){
          let form = {
            groupId: localStorage.getItem('SET_GROUP_ID'),
            orgId: localStorage.getItem('SET_ORG_ID'),
            tableColumn: this.menusOne.tableName + '_' + arr[i].column,
            applicationCode: this.applicationCode,
            parentCode: parentCode
          }
          arr[i].value = '';
          let res = await commonApi.number(form);
          if (res.data !== null&& res.data.readonly ===true) {
            arr[i].value = res.data.retCode;
            arr[i].disabled = true
            arr[i].isCustomValue = true
            this.codeRules[arr[i].prop] = res.data.id
          }
        }
      }
    },
    getPurchaseContractApi (titleField) {
      return new Promise((resolve,reject)=>{
        purchaseContractApi.findOptions({sortBy: 'id',sortOrder: 'desc',q: '',}).then(res => {
        this.options.purchaseContract = res.data.map(entity => ({label: entity[titleField], value: entity.id}))
          resolve()
        })
      })
      },
     
    // 组装数据
    genDynTable(objData){
      // FIXME 上线时改为userinfoss  处理按钮权限
      let {functions} = JSON.parse(sessionStorage.getItem('userinfos')) || {};
      if (!functions) {
        functions = [];
      }
      objData.listBtnObj = objData.listBtnObj.filter(btn => functions.indexOf(btn.code) !== -1)
      
      this.dynTableData.listBtnObj = objData.listBtnObj
      this.dynTableData.listTable = objData.listTable
      //获取字典项
      let dictionaryEntry = JSON.parse(sessionStorage.getItem('constCode'))
      if(!dictionaryEntry){
        dictionaryEntry = []
      }
      objData.listTable.tableHeader.forEach(headerField => {
        // 组装枚举数据
        if(headerField.fieldSpecialType === specialAttr.fieldSpecialType.ENUM_TYPE.code){
          console.log('ENUM_TYPE',headerField.dicTypeData)
          if(headerField.filtered){
            // headerField.filterQuery.options = this.$store.getters.dictList[headerField.dicTypeData].map(item => ({ label: item.name, value: item.value}))
            headerField.filterQuery.options = []
            dictionaryEntry.forEach((item) => {
              if(item.constCode == headerField.dicTypeData){
                headerField.filterQuery.options.push({ label: item.name, value: item.value })
              }
            })
            console.log('headerField.filterQuery.options',headerField.filterQuery.options)
          }
          // 方法名称
          headerField.webFilter = 'findEnumLabel'
          // 数组名称
          // headerField.webFilterArr = this.$store.getters.dictList[headerField.dicTypeData].map(item => ({ label: item.name, value: item.value}))
          headerField.webFilterArr = []
          dictionaryEntry.forEach((item) => {
            if(item.constCode == headerField.dicTypeData){
              headerField.webFilterArr.push({ label: item.name, value: item.value })
            }
          })
          // 属性名称(枚举不需要属性名称)
          headerField.webFilterProp = 'label'
          headerField.webFilterValue = 'value'
        // 组装外键数据
        }else if(headerField.fieldSpecialType === specialAttr.fieldSpecialType.FK_TYPE.code){
          console.log('FK_TYPE')
          if(headerField.filtered){
            headerField.filterQuery.options = this.options[headerField.foreignData]
          }
          // 方法名称
          headerField.webFilter = 'findForeignKey'
          // 数组名称
          headerField.webFilterArr = this.options[headerField.foreignData]
          // 属性名称
          headerField.webFilterProp = 'label'
          //对比值
          headerField.webFilterValue = 'value'
          if (headerField.isTree) {
          headerField.webFilterValue = 'id'
          }
        }
        // 组装其他数据
        else if(headerField.fieldSpecialType === specialAttr.fieldSpecialType.OTHER_WEB.code){
          console.log('OTHER_WEB')
          if(headerField.filtered){
            headerField.filterQuery.options = this.options[headerField.webEntityData]
          }
        }
        if(headerField.column.indexOf("workflowState") != -1){
          // 方法名称
          headerField.webFilter = 'findEnumLabel'
          // 数组名称
          // headerField.webFilterArr = this.$store.getters.dictList[headerField.dicTypeData].map(item => ({ label: item.name, value: item.value}))
          headerField.webFilterArr = [
            { label: '执行中', value: 0 },
            { label: '草稿', value: 1 },
            { label: '驳回', value: 2 },
            { label: '提交', value: 3 },
            { label: '通过', value: 4 },
            { label: '不通过', value: 5 },
            { label: '完成', value: 6 },
          ]
          // 属性名称(枚举不需要属性名称)
          headerField.webFilterProp = 'label'
          headerField.webFilterValue = 'value'
        }
      })
      // 获取行内按钮集合
      objData.listBtnObj.forEach(item=> {
          if(item.isLine === true){
              item.isShow = true
              this.dynTableData.inLineBtnList.push(item)
          }
      })

      if (this.showPage) {
        this.doQueryList({ page: 1 })
      } else {
        this.doQueryList({})
      }
    },
    /**
     * 触发后端排序
     */
    sortChange({ name, order }) {
      this.$set(this.query,'sortBy',name)
      if (order === 'ascending') {
        this.$set(this.query,'sortOrder','asc')
      } else {
        this.$set(this.query,'sortOrder','desc')
      }
      if (this.showPage) {
        this.doQueryList({ page: 1 })
      } else {
        this.doQueryList({})
      }
    },
    /**
     * 触发搜索操作
     */
    handleQuery(queryVariable) {
      this.$set(this.query,'q',queryToString(queryVariable))
      if (this.showPage) {
        this.doQueryList({ page: 1  })
      } else {
        this.doQueryList({})
      }
      
    },
    //拖拽区确定按钮
    handleDrags(tableHeaders){
      let dynTableHeader = []
      tableHeaders.forEach(item => {
        let header = {
          column: item.column,
          showed: item.showed,
          fixed: item.fixed,
          filtered: item.filtered
        }
        dynTableHeader.push(header)
      })
      let {tenantId, groupId, orgId, userId, account} = JSON.parse(sessionStorage.getItem('userinfos')) || {};
      let customTableColumn = {
        id: null,
        menuCode: sessionStorage.getItem('routerCode'),
        tenantId: tenantId,
        groupId: groupId,
        orgId: orgId,
        userId: userId,
        account: account,
        dynTableHeader: dynTableHeader
      }
      tableConfigApi.saveCustomTableColumn(customTableColumn).then(res => {
        if (res.code === '000000') {
          this.$message({
            type: 'success',
            message: '保存成功!'
          })
          this.dynTableData.listTable.tableHeader = JSON.parse(JSON.stringify(tableHeaders))
          this.$nextTick(()=>{
            this.$refs.dynTableBox.doLayoutTable()
          })
          // 刷新动态表单表格
          dynTableApi.getDynTable(tenantId).then(res => {
            sessionStorage.setItem("routerMenus", JSON.stringify(res.data));
          }).catch(err => {
            console.log(err)
          })
          if (this.showPage) {
            this.doQueryList({ page: 1  })
          } else {
            this.doQueryList({ })
          }
        } else {
          this.$message({
            type: 'error',
            message: res.message
          })
        }
      })
    },
    // 重置按钮方法
    handleReset() {
      this.query = {
        pageNum: 1,
        pageSize: 20,
        sortBy: 'id',
        sortOrder: 'desc',
        q: ''
      }
      if (this.showPage) {
        this.doQueryList({ page: 1 })
      }else {
        this.doQueryList({})
      }
    },
    //分页
    handlePage(param){
      this.doQueryList({ page: param.pageNum, limit: param.pageSize })
    },
    /**
     * 执行列表查询
     */
    async doQueryList({ page, limit }) {

      if (this.showPage) {
        if (page) {
          this.query.pageNum = page
        }
        if (limit) {
          this.query.pageSize = limit
        }
      }

      this.listLoading = true

      let args = Object.assign({}, this.query)
      try {
       let res;
       let list;
       let total;
      if (this.showPage) {
        res = await purchaseContractFileInfoApi.finds(args)
        list = res.data.list
        total = res.data.total
      } else {
        args.pageNum = null
        args.pageSize = null
        res = await purchaseContractFileInfoApi.findOptions(args)
        list = res.data
        total = res.data.length
      }
      list.forEach(item=>{
        if(item.extension){
          item = Object.assign(item,JSON.parse(item.extension))
        }
        item.operation = JSON.parse(JSON.stringify(this.dynTableData.inLineBtnList))
        item.operation.forEach(op =>{
          if (op.isStarted) {
            let {label, labelFalse} = op;
            if (!item[op.code]) {
              op.label = labelFalse;
            }
            item[op.code] = item[op.code] ? labelFalse : label
          }
        })
      })
      this.$set(this.dynTableData.listTable,'total',total)
      this.$set(this.dynTableData.listTable,'tableData',list)
      this.$refs.dynTableBox.handleRefresh()
    } catch(err) {
      console.error(err)
    }
    },
    /**
     * 删除单条记录
     */
    handleDeleteSingle(row) {
      return this.$common.confirm('是否确认删除')
        .then(() => {
          this.listLoading = true
          purchaseContractFileInfoApi.del(row.id)
          .then(() => {
                this.$common.showMsg('success', '删除成功')
                if (this.showPage) {
                  return this.doQueryList({ page: 1 })
                } else {
                  return this.doQueryList({})
                }
          })
        })
        .catch(() => {
          this.$message({type: 'info',message: '已取消删除'})
        })
    },
    /**
     * 批量删除记录
     */
    handleDeleteBatch(listRow) {
      if (listRow.length <= 0) {
        this.$common.showMsg('warning', '请选择')
        return
      }
      return this.$common.confirm('是否确认删除')
        .then(() =>{
            this.listLoading = true
            purchaseContractFileInfoApi.deleteBatch(listRow.map(row => row.id))
            .then(() => {
                this.$common.showMsg('success', '删除成功')
                if (this.showPage) {
                  return this.doQueryList({ page: 1 })
                } else {
                  return this.doQueryList({})
                }
            }).catch(()=>{
                this.listLoading = false
            })
        }).catch(() => {
              this.$message({
              type: 'info',
              message: '已取消删除'
          })
        })
    },


    /**
     * 打开新建表单
     */
    handleCreate() {
      this.$refs.purchaseContractFileInfoAdd.handleCreate(this.menusOne,this.codeRules)
    },
    /**
     * 打开子菜单
     */
    async handleCreateChild(row) {
      await this.handleCode(row.code)
      this.$refs.purchaseContractFileInfoAdd.handleCreate(this.treeOptions,row,this.menusOne,this.codeRules)
    },
    /**
     * 打开查看表单
     */
    handleShow(row) {
      this.$refs.purchaseContractFileInfoShow.handleShow(row,this.menusOne)
    },
    /**
     * 打开编辑表单
     */
    handleUpdate(row) {
      this.$refs.purchaseContractFileInfoEdit.handleUpdate(row,this.menusOne)
    }
  }
}
</script>
